package textui.example;

import static textui.ElementSelector.ReduceVerbosity.element;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import textui.ElementSelector;
import textui.ProxyUIElement;
import textui.SelectorElement;
import textui.UIElement;
import textui.UIElementBuilder;

public class MenuBuilder implements UIElementBuilder {

	private Map<String, UIElementBuilder> _items=new HashMap<String, UIElementBuilder>();
	private final ProxyUIElement _element = new ProxyUIElement(null);
	private boolean firstRun = true;
	
	public void addMenuItem(String string) {
		_items.put(string, null);

	}

	public void link(String s, UIElementBuilder b) {
		_items.put(s, b);
	}

	@Override
	public UIElement build() {
		if (!firstRun)
			return _element;
		firstRun = false;
		satisfaction();
		final ElementSelector<SelectorElement<UIElement>> v = new ElementSelector<SelectorElement<UIElement>>(
				parse(_items));
		_element.setElement(new UIElement(null) {

			@Override
			public UIElement run() {

				return v.select().get();
			}
		});
		return _element;
	}

	private List<SelectorElement<UIElement>> parse(
			Map<String, UIElementBuilder> _items2) {
		List<SelectorElement<UIElement>> rv = new ArrayList<>();
		for (Map.Entry<String, UIElementBuilder> entry : _items.entrySet())
			rv.add(element(entry.getValue().build(), entry.getKey()));
		return rv;
	}

	private void satisfaction() {
		for (Map.Entry<String, UIElementBuilder> entry : _items.entrySet())
			if (entry.getValue() == null)
				throw new Error("No Entry for key :" + entry.getKey());
	}

}
